package com.hghivln.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hghivln.constants.Constants;
import com.hghivln.mapper.DeptMapper;
import com.hghivln.pojo.domain.Dept;
import com.hghivln.pojo.dto.DeptDto;
import com.hghivln.pojo.vo.AjaxResult;
import com.hghivln.service.DeptService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService{

    @Autowired
    private DeptMapper deptMapper;

    @Override
    public AjaxResult listDeptForPage(DeptDto deptDto) {
        Page<Dept> page = new Page<>(deptDto.getPageNum(),deptDto.getPageSize());
        QueryWrapper<Dept> qw = new QueryWrapper<>();
        qw.like(StringUtils.isNotBlank(deptDto.getDeptName()),Dept.COL_DEPT_NAME,deptDto.getDeptName());
        qw.eq(StringUtils.isNotBlank(deptDto.getStatus()),Dept.COL_STATUS,deptDto.getStatus());
        qw.ge(deptDto.getBeginTime() != null,Dept.COL_CREATE_TIME,deptDto.getBeginTime());
        qw.le(deptDto.getEndTime() != null,Dept.COL_CREATE_TIME,deptDto.getEndTime());
        qw.eq(Dept.COL_DEL_FLAG, Constants.DEL_FALSE);
        qw.orderByAsc(Dept.COL_ORDER_NUM);
        deptMapper.selectPage(page,qw);
        return AjaxResult.success("查询成功",page.getRecords(),page.getTotal());
    }

    @Override
    public int addDept(DeptDto deptDto) {
        Dept dept = new Dept();
        BeanUtils.copyProperties(deptDto,dept);
        dept.setCreateTime(DateUtil.date());
        dept.setCreateBy(deptDto.getSimpleUser().getUserName());
        return deptMapper.insert(dept);
    }

    @Override
    public int updateDept(DeptDto deptDto) {
        Dept dept = new Dept();
        BeanUtils.copyProperties(deptDto,dept);
        dept.setUpdateBy(deptDto.getSimpleUser().getUserName());
        return deptMapper.updateById(dept);
    }

    @Override
    public int deleteDeptByIds(Long[] ids) {
        List<Long> idList = Arrays.asList(ids);
        if (idList.size()>0) {
            return deptMapper.deleteByIds(idList);
        }
        return 0;
    }

    @Override
    public AjaxResult getDeptById(Long id) {
        return AjaxResult.success(deptMapper.selectById(id));
    }

    @Override
    public AjaxResult selectAllDept() {
        QueryWrapper<Dept> qw = new QueryWrapper<>();
        qw.eq(Dept.COL_STATUS,Constants.STATUS_TRUE);
        qw.eq(Dept.COL_DEL_FLAG,0);
        qw.orderByAsc(Dept.COL_ORDER_NUM);
        return AjaxResult.success(deptMapper.selectList(qw));
    }
}
